package com.fz.security.provider;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fz.common.Global;
import com.fz.common.ResultCode;
import com.fz.dto.client.login.WxAuthDto;
import com.fz.entity.member.Member;
import com.fz.mapper.member.MemberMapper;
import com.fz.security.AuthExceptionDto;
import com.fz.utils.JacksonUtils;
import com.fz.utils.RedisUtil;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

@Component
public class InitUserProvider {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private MemberMapper memberMapper;
    /**
     * @方法描述: 用于处理微信与小程序授权后作为注册用户处理方法
     * @参数:   wxAuthDto 授权后参数  authType 1代表微信授权 2代表小程序授权
     * @返回值:
     * @创建人: I am God
     * @创建时间:: 2021/2/26
     */
    public Member initMember(WxAuthDto wxAuthDto,String authType){
        //验证短信验证码是否正确
        String captcha = "";
        String key = Global.LOGIN_MSG_CODE_KEY + wxAuthDto.getMobilePhone();
        if (redisUtil.hasKey(key)) {
            captcha = (String) redisUtil.get(key);
        }
        if (!wxAuthDto.getCode().equals(captcha)) {
            throw new BadCredentialsException(JacksonUtils.obj2String(new AuthExceptionDto(ResultCode.MSG_CODE_ERROR.getResultCode(), ResultCode.MSG_CODE_ERROR.getMessage())));
        }
        //查看用户手机号是否已存在
        LambdaQueryWrapper<Member> lambdaQueryWrapper = Wrappers.lambdaQuery();
        lambdaQueryWrapper.eq(Member::getMobilePhone,wxAuthDto.getMobilePhone());
        Member member = memberMapper.selectOne(lambdaQueryWrapper);
        if (null == member) {
            //若用户确实不存在则进行注册
            member = new Member();
            member.setMobilePhone(wxAuthDto.getMobilePhone());
            member.setUnionId(wxAuthDto.getUnionId());
            if(authType.equals("1")){
                member.setAppOpenId(wxAuthDto.getOpenId());
            }else{
                member.setAppletOpenId(wxAuthDto.getOpenId());
            }
            //等集成文件存储之后再改动
            member.setAvatarUrl(wxAuthDto.getAvatarUrl());
            memberMapper.insert(member);
        }else{
            //若用户手机号已存在，则对用户的unionid及openid进行更新
            member.setUnionId(wxAuthDto.getUnionId());
            if(authType.equals("1")){
                member.setAppOpenId(wxAuthDto.getOpenId());
            }else{
                member.setAppletOpenId(wxAuthDto.getOpenId());
            }
            memberMapper.updateById(member);
        }
        return member;
    }
}
